class Solution
{
public:
    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity)
    {
        unordered_set<long long> seen;
        queue<pair<int, int>> q;
        q.push({0, 0});

        while (!q.empty())
        {
            auto [x, y] = q.front();
            q.pop();

            if (x + y == targetCapacity || x == targetCapacity || y == targetCapacity)
            {
                return true;
            }

            long long key = x * 1000000LL + y;
            if (seen.count(key))
            {
                continue;
            }
            seen.insert(key);

            q.push({0, y});
            q.push({x, 0});
            q.push({jug1Capacity, y});
            q.push({x, jug2Capacity});
            q.push({x - min(x, jug2Capacity - y), y + min(x, jug2Capacity - y)});
            q.push({x + min(y, jug1Capacity - x), y - min(y, jug1Capacity - x)});
        }
        return false;
    }
};